<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="maindialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-table
              :data="order_datas"
            >
              <el-table-column align="center" label="订单信息">
                <template slot-scope="scope">
                  <div style="display: block;text-align:left;">
                    <img
                      v-for="(item,index) in scope.row.products"
                      v-if="scope.row.products.length > 0"
                      :key="index"
                      :src="item.image"
                      style="max-width: 50px; max-height: 50px"
                    >
                    <span style="display: block">{{ scope.row.domain }}</span>
                    <span style="display: block"> {{ scope.row.currency }}{{ scope.row.total_paid }} 运费:<span
                      style="color:#FF0000"
                    >{{ scope.row.currency }}{{ scope.row.total_shipping }}</span></span>
                    <span style="color:#FF0000;display: block">
                      <i class="el-icon-date">{{ scope.row.create_at.split('T')[0] }}</i>
                      <i class="el-icon-time">{{ scope.row.create_at.split('T')[1] }}</i>
                    </span>
                    <span style="display: block">备注:{{ scope.row.note }}</span>
                    <span style="display: block">订单状态:{{ scope.row.state_name }}</span>
                    <span
                      style="display: block"
                    >{{ scope.row.payment_name }}账号:{{ scope.row.paypal_api_account }}</span>
                    <span style="display: block">交易号: {{ scope.row.id_transaction }}</span>
                  </div>
                  <hr>
                  <ul
                    v-for="(item,index) in scope.row.trackings"
                    v-if="scope.row.trackings.length > 0"
                    :key="index"
                    style="padding-left: 0px;text-align:left;"
                  >
                    <li v-if="item.dropshipping_account !== ''" style="list-style:none">
                      下单账号:{{ item.dropshipping_account }}
                    </li>
                    <li v-if="item.carrier !== ''" style="list-style:none">快递:{{ item.carrier }}</li>
                    <li v-if="item.dropshipping_order_id !== ''" style="list-style:none">
                      订单ID:
                      <a
                        target="_blank"
                        :href="'https://trade.aliexpress.com/order_detail.htm?&orderId='+item.dropshipping_order_id"
                      >{{ item.dropshipping_order_id }}</a>
                    </li>
                    <li v-if="item.order_state !== ''" style="list-style:none">{{ item.order_state }}</li>
                    <li v-if="item.tracking_no !== ''" style="list-style:none">
                      跟踪单号:<span v-if="item.tracking_url !== ''"><a
                        :href="'https://global.cainiao.com/detail.htm?mailNoList=' + scope.row.tracking_no"
                        target="_blank"
                      >{{ item.tracking_no }}</a></span>
                      <span v-else>{{ item.tracking_no }}</span></li>
                    <li v-if="item.specify_tracking_no !== ''" style="list-style:none">
                      指定跟踪单号:<span v-if="item.specify_tracking_no !== ''"><a
                        :href="'https://t.17track.net/en#nums=' + item.specify_tracking_no"
                        target="_blank"
                      >{{ item.specify_tracking_no }}</a></span>
                      <span v-else>{{ item.specify_tracking_no }}</span>
                    </li>
                    <li v-if="item.order_at !== ''" style="list-style:none">{{ item.order_at }}</li>
                    <li>备注:{{ scope.row.note }}</li>
                  </ul>
                </template>
              </el-table-column>
            </el-table>
            <ul v-for="(item,index) in paypalcase_data" v-if="paypalcase_data.length > 0" :key="index">
              <li style="list-style:none">事件编号: {{ item.case_id }}</li>
              <li style="list-style:none"> 邮件主题: {{ item.last_subject }}</li>
              <li style="list-style:none"> 更新时间: {{ item.update_at }}</li>
            </ul>
          </div>
        </el-col>
        <el-col :span="18">
          <el-form ref="dataForm" :model="replyemail" label-position="left" label-width="80px">
            <el-form-item label="收件人">
              <el-input v-model="replyemail.receiver_email">
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  title="查询订单信息"
                  @click="handleSearchOrderInfo(replyemail.receiver_email)"
                >订单
                </el-button>
              </el-input>

            </el-form-item>
            <el-form-item label="发件人">
              <el-input v-model="replyemail.sender_mail" />
            </el-form-item>
            <el-form-item label="">
              <el-switch
                v-model="replyemail.local_send"
                active-color="#13ce66"
                active-text="通过本地账号发送"
                inactive-text="通过绑邮箱发送"
                inactive-color="#ff4949"
              />
            </el-form-item>
            <el-form-item v-if="replyemail.local_send" label="本地账号">
              <el-select
                v-model="replyemail.send_account"
                clearable
                filterable
              >
                <el-option
                  v-for="(item,index) in email_accounts"
                  :key="index"
                  :label="item.account"
                  :value="item.id"
                />
              </el-select>
              <span v-if="replyemail.send_account===''" style="margin-left: 5px">不选择发送邮箱,会根据情况自动选择</span>
            </el-form-item>
            <el-form-item v-else label="绑定邮箱">
              <el-select
                v-model="replyemail.gmail"
                clearable
                filterable
              >
                <el-option
                  v-for="(item,index) in gmails"
                  :key="index"
                  :label="item.gmail"
                  :value="item.gmail"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="回复模板">
              <el-checkbox v-model="replayTemplateAll">所有人</el-checkbox>
              <el-select
                v-model="chooseReplayTemplate"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索模板"
                :remote-method="searchReplayTemplate"
                :loading="replatemplateloading"
                @change="handleChangeTemplate"
              >
                <el-option
                  v-for="(item,index) in replaytemplateoptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-popover
                placement="top"
                width="640"
                trigger="hover"
              >
                <div>
                  <p style="margin-top: 10px">{{ replaytemplatebody }}></p>
                </div>
                <i slot="reference" class="el-icon-view" title="查看详情" />
              </el-popover>
              <el-button icon="el-icon-plus" @click="handleInsertTemplate">插入</el-button>
            </el-form-item>
            <el-form-item label="Subject">
              <el-input v-model="replyemail.subject" />
            </el-form-item>
            <el-form-item label="邮件内容">
              <tinymce ref="mt" v-model="replyemail.body" :height="300" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="maindialogVisible = false">取 消</el-button>
        <el-button type="success" @click="handleSendMail">发 送</el-button>
      </span>
    </el-dialog>
    <orderinfo
      :keyword="orderinfokeyword"
      :orderinfo-visible="orderinfoVisible"
      @closeDialog="orderinfoVisible=false"
    />
    <replytemplate :dialog-visible="replayConfigDialogVisible" @close="replayConfigDialogVisible=false" />
  </div>
</template>

<script>
import { Get as GetOrders } from '@/api/orders/psorder'
import { Get as GetPaypalCase } from '@/api/eco/paypalcase'
import { Get as GetReplayTemplate, AddUsed } from '@/api/eco/replytemplate'
import { SendEmail } from '@/api/eco/email'
import Tinymce from '@/components/Tinymce'
import Orderinfo from '../../orders/element/orderinfo'
import Replytemplate from './replytemplate'
import { Get as GetEmailAccounts } from '@/api/eco/email'
import { Get as GetGmails } from '@/api/orders/googlegmailaccount'

import qs from 'qs'

export default {
  name: 'Sendmail',
  components: { Replytemplate, Orderinfo, Tinymce },
  props: ['dialogVisible', 'mail_receiver', 'mail_to', 'pre_subject', 'pre_body', 'emailbox_id'],
  data() {
    return {
      data: [],
      title: '回复邮件',
      listLoading: true,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      maindialogVisible: false,
      chooseReplayTemplate: '',
      orderinfokeyword: '',
      replayTemplateAll: true,
      replaytemplateoptions: [],
      replaytemplatebody: '',
      replyemail: {
        local_send: false,
        sender_mail: '',
        emailbox_id: '',
        gmail: '',
        body: '',
        subject: '',
        send_account: '',
        receiver_email: '',
        server_type: 'local'
      },
      email_accounts: [],
      order_datas: [],
      order_total: 0,
      orderloading: false,
      paypalcase_data: [],
      orderinfoVisible: false,
      replayConfigDialogVisible: false,
      gmails: []
    }
  },
  watch: {
    dialogVisible(v) {
      this.maindialogVisible = v
    },
    mail_to(v) {
      this.replyemail.receiver_email = v
      if (v) {
        this.GetOrderInfomation(v)
      }
    },
    mail_receiver(v) {
      this.handleGetBindMails(v)
    },
    emailbox_id(v) {
      this.replyemail.emailbox_id = v
    },
    pre_subject(v) {
      this.replyemail.subject = v
    },
    pre_body(v) {
      this.replyemail.body = v
      this.$nextTick(() => {
        if (this.$refs.mt.hasInit) {
          this.$refs.mt.setContent(this.replyemail.body)
        }
      })
    }
  },
  created() {
    this.getReplyTemplate({ 'kw': '', 'pagesize': 20 })
    this.handleGetEmailAccounts()
  },
  methods: {
    handleGetBindMails() {
      const domain = this.mail_receiver.split('@')
      if (domain.length < 2) {
        console.log('domain not valid')
        return
      }
      this.replyemail.sender_mail = 'sales@' + domain[1]
      GetGmails(null, qs.stringify({
        kw: domain[1],
        sendable: true
      }))
        .then(response => {
          this.gmails = response.data.data
          if (this.gmails.length > 0) {
            this.replyemail.gmail = this.gmails[0].gmail
          }
        }).catch(err => {
          console.log(err)
        })
    },
    handleGetGmails(domain) {
      GetGmails(null, qs.stringify({
        kw: domain,
        sendable: true
      }))
        .then(response => {
          this.gmails = response.data.data
          if (this.gmails.length > 0) {
            this.replyemail.gmail = this.gmails[0].gmail
            this.replyemail.local_send = false
          }
        }).catch(err => {
          console.log(err)
        })
    },
    handleGetEmailAccounts() {
      GetEmailAccounts(null, qs.stringify({
        kw: '',
        sendable: true
      }))
        .then(response => {
          this.email_accounts = response.data.data
          console.log('email:', this.email_accounts)
        }).catch(err => {
          console.log(err)
        })
    },
    handleSendMail() {
      // 新增邮件内型，统一接口
      if (this.replyemail.local_send) {
        this.replyemail.server_type = 'local'
      } else {
        this.replyemail.server_type = 'gsapi_gmail'
        // SendMailByGmail(this.replyemail
        // ).then(response => {
        //   this.maindialogVisible = false
        //   this.notify('发送成功')
        // })
      }
      SendEmail(this.replyemail).then(response => {
        this.maindialogVisible = false
        this.notify('发送成功')
      })
    },
    handleChangeTemplate(id) {
      this.replaytemplateoptions.forEach(item => {
        if (id === this.chooseReplayTemplate) {
          this.replaytemplatebody = item.body
        }
      })
    },
    changeTeamplate(content) {
      if (this.order_datas.length > 0) {
        if (this.order_datas[0].trackings.length > 0) {
          let tracking_msg = ''
          this.order_datas[0].trackings.forEach(item => {
            const tracing_no = item.specify_tracking_no !== '' ? item.specify_tracking_no : item.tracking_no
            tracking_msg = tracking_msg + '<a target="_blank" href="https://t.17track.net/en#nums=' + tracing_no + '">' + tracing_no + '</a>&nbsp;&nbsp;'
          })
          content = content.replace('#tracking_url#', tracking_msg)
        }
        if (this.order_datas[0].paypal_api_account !== '') {
          content = content.replace('#paypal_account#', this.order_datas[0].paypal_api_account)
        }
        if (this.order_datas[0].products.length > 0) {
          let _msg = ''
          this.order_datas[0].products.forEach(item => {
            _msg = _msg + "<a target='_blank' href='" + item.ps_url + "'>" + item.ps_url + '</a>&nbsp;&nbsp;'
          })
          content = content.replace('#product_url#', _msg)
        }
      }
      return content
    },
    handleInsertTemplate() {
      if (this.chooseReplayTemplate !== '') {
        this.replaytemplateoptions.forEach(item => {
          if (item.value === this.chooseReplayTemplate) {
            AddUsed(this.chooseReplayTemplate, {})
            this.replyemail.body = item.body.replace(/(?:\ r\n|\r|\n)/g, '<br>') + '&nbsp;&nbsp;<br>' + this.replyemail.body
            this.replyemail.body = this.changeTeamplate(this.replyemail.body)
            this.$nextTick(() => {
              if (this.$refs.mt.hasInit) {
                this.$refs.mt.setContent(this.replyemail.body)
              }
            })
          }
        })
      }
    },
    getReplyTemplate(data) {
      this.replatemplateloading = true
      this.replaytemplateoptions = []
      if (this.replayTemplateAll) {
        data['all'] = true
      } else {
        data['all'] = false
      }
      GetReplayTemplate(null, qs.stringify(data)).then(response => {
        response.data.data.forEach(item => {
          this.replaytemplateoptions.push({ 'label': item.name, 'value': item.id, 'body': item.body })
        })
        this.replatemplateloading = false
      }
      ).catch(error => {
        this.replatemplateloading = false
        console.log(error)
      })
    },
    searchReplayTemplate(query) {
      if (query !== '') {
        console.log(query)
        this.getReplyTemplate({ 'kw': query })
      }
    },
    handleSearchOrderInfo(email) {
      this.orderinfokeyword = email
      this.orderinfoVisible = true
      console.log(email)
    },
    GetPaypalCaseInfo(transaction_id) {
      GetPaypalCase(null, qs.stringify({
        transaction_id: transaction_id
      }))
        .then(response => {
          this.scrollTop()
          this.paypalcase_data = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    GetOrderInfomation(keyword) {
      this.order_datas = []
      this.paypalcase_data = []
      GetOrders(null, qs.stringify({
        kw: keyword
      })).then(response => {
        this.order_datas = response.data.data
        this.total_sales = 0
        this.order_datas.forEach((row) => {
          this.total_sales += row.total_paid
        })
        this.total = response.data.total
        // 获取paypalcase
        if (this.order_datas.length > 0) {
          // 获取gmail账号
          this.handleGetGmails(this.order_datas[0].domain)
          if (this.order_datas[0].id_transaction) {
            this.GetPaypalCaseInfo(this.order_datas[0].id_transaction)
          }
        }
        // end
      }).catch(error => {
        this.loading = false
        this.$message({
          type: 'error',
          message: error
        })
      })
    },
    close() {
      this.$emit('close', this.replyemail.emailbox_id)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-input {
  width: auto;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 5px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 5px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin: 10px auto !important;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 60px;
  padding-top: 5px;
}

.top >>> .el-select {
  width: 300px;
}

</style>
